package com.googlecode.yoohoo.xmppcore.protocol.parsing.error;

import java.util.List;

import com.googlecode.yoohoo.xmppcore.protocol.XmlLangText;
import com.googlecode.yoohoo.xmppcore.protocol.XmppProtocolException;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.Attribute;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.IXmppParser;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.IXmppParserFactory;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.XmppParserAdapter;
import com.googlecode.yoohoo.xmppcore.protocol.stanza.error.BadRequest;

public abstract class ErrorDetailsParserFactory implements IXmppParserFactory<Object> {
	@Override
	public IXmppParser<Object> createParser() {
		return new ErrorDetailParser();
	}

	private class ErrorDetailParser extends XmppParserAdapter<Object> {
		private static final String PATH_TEXT = "text";
		private static final String ATTRIBUTE_LOCAL_NAME_LANG = "lang";
		private static final String ATTRIBUTE_NAMESPACE_XML = "xml";
		private Object object;

		@Override
		public Object getObject() {
			return object;
		}
		
		@Override
		public void processAttributes(String path, List<Attribute> attributes) {
			if (PATH_TEXT.equals(path)) {
				if (attributes.size() > 1) {
					throw new XmppProtocolException(new BadRequest("Element 'text' only support 'xml:lang' attribute."));
				}
				
				XmlLangText text = new XmlLangText();
				if (attributes.size() == 1) {
					if (!ATTRIBUTE_NAMESPACE_XML.equals(attributes.get(0).getPrefix()) ||
							!ATTRIBUTE_LOCAL_NAME_LANG.equals(attributes.get(0).getLocalName())) {
						throw new XmppProtocolException(new BadRequest("Element 'text' only support 'xml:lang' attribute."));
					}
					
					text.setXmlLang(attributes.get(0).getValue());
				}
				
				object = text;
			} else {
				object = path;
			}
		}
		
		@Override
		public void processText(String path, String text) {
			if (PATH_TEXT.equals(path)) {
				((XmlLangText)object).setText(text);
			}
		}
	}
}
